#include <pthread.h> // 带入线程库
#include <iostream>
#include <unistd.h>

// 条件变量和互斥锁
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_A = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond_B = PTHREAD_COND_INITIALIZER;
int count = false; // 控制打印轮次的变量

// 线程A的打印函数
void *print_A(void *arg)
{
    while (true)
    {
        pthread_mutex_lock(&lock);
        while (count != false)
        {
            // 阻塞时会释放锁，唤醒时会重新获得锁并执行
            pthread_cond_wait(&cond_A, &lock);
        }

        std::cout << "I am thread A" << std::endl;

        // 切换到线程B
        count = true;
        pthread_cond_signal(&cond_B); // 通知线程B
        pthread_mutex_unlock(&lock);

        sleep(1); // 放刷屏，打印慢点
    }
}

// 线程B的打印函数
void *print_B(void *arg)
{
    while (true)
    {
        pthread_mutex_lock(&lock);
        while (count != true)
        {
            // 阻塞时会释放锁，唤醒时会重新获得锁并执行
            pthread_cond_wait(&cond_B, &lock);
        }
        std::cout << "I am thread B" << std::endl;

        // 切换到线程A
        count = false;
        pthread_cond_signal(&cond_A); // 通知线程A
        pthread_mutex_unlock(&lock);

        sleep(1); // 放刷屏，打印慢点
    }
}

int main()
{
    pthread_t tid_A, tid_B;

    // 创建线程
    pthread_create(&tid_A, nullptr, print_A, nullptr);
    pthread_create(&tid_B, nullptr, print_B, nullptr);

    pthread_join(tid_A, nullptr);
    pthread_join(tid_B, nullptr);

    pthread_mutex_destroy(&lock);
    pthread_cond_destroy(&cond_A);
    pthread_cond_destroy(&cond_B);

    return 0;
}


#include <pthread.h> // 带入线程库
#include <iostream>
#include <unistd.h>

// 条件变量和互斥锁
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void *group_leader(void *args)
{
    while (true)
    {
        std::cout << "I am thread-A, assign tasks:" << std::endl;
        pthread_cond_broadcast(&cond);

        sleep(1);
    }
}

void *team_members(void *args)
{
    std::string name = *((std::string*)args);
    while (true)
    {
        pthread_mutex_lock(&lock);
        pthread_cond_wait(&cond, &lock);
        std::cout << name << " is running..." << std::endl;

        pthread_mutex_unlock(&lock);
    }
}

const int N = 3;

int main()
{
    pthread_t tid[N], tid_1;

    // 创建线程

    pthread_create(&tid_1, nullptr, group_leader, nullptr);

    for (int i = 0; i < N; i++)
    {
        std::string *name = new std::string("thread-" + std::to_string(i + 1));
        pthread_create(tid + i, nullptr, team_members, name); // name已经是地址了，可以直接传
    }

    for (int i = 0; i < N; i++)
    {
        pthread_join(tid[i], nullptr);
    }

    pthread_join(tid_1, nullptr);

    pthread_mutex_destroy(&lock);
    pthread_cond_destroy(&cond);

    return 0;
}


